<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/22
 * Time: 上午8:21
 */

namespace app\admin\controller;

use app\common\model\Copy;
use think\Exception;
use think\Db;
use app\common\model\Message;
use app\common\model\Settings;

class Goods extends Common
{
    //商品列表
    public function index()
    {
        $this->templateTitle('商品列表');
        $this->assign('level', get_category_level());
        //判断条件
        $where = [];

        $id = trim(request()->param('id'));
        $this->assign('id', $id);
        if (!empty($id)) {
            $where['g.id'] = intval($id);
        }

        //商品标题
        $title = request()->param("title");
        $this->assign("title", $title);
        if ($title) {
            $where["g.title"] = ["LIKE", "%$title%"];
        }

        //所属分类
        $category_id1 = trim(request()->param('category_id1'));
        $this->assign('category_id1', $category_id1);
        if ($category_id1) {
            $where['g.category_id1'] = intval($category_id1);
        }

        //所属分类
        $category_id2 = trim(request()->param('category_id2'));
        $this->assign('category_id2', $category_id2);
        if ($category_id2) {
            $where['g.category_id2'] = intval($category_id2);
        }

        //所属分类
        $category_id3 = trim(request()->param('category_id3'));
        $this->assign('category_id3', $category_id3);
        if ($category_id3) {
            $where['g.category_id3'] = intval($category_id3);
        }

        //是否上下架
        $status = trim(request()->param('status'));
        $this->assign('status', $status);
        if ($status != '') {
            $where['g.status'] = intval($status);
        }

        //获取商品列表
        $list = Db::name("sell_goods")
            ->alias('g')
            ->join('__CATEGORY__ c1', 'c1.id=g.category_id1', 'LEFT')
            ->join('__CATEGORY__ c2', 'c2.id=g.category_id2', 'LEFT')
            ->join('__CATEGORY__ c3', 'c3.id=g.category_id3', 'LEFT')
            ->where($where)
            ->field('g.*,c1.title as c1_title,c1.is_visible as c1_visible,c2.title as c2_title,c2.is_visible as c2_visible,c3.title as c3_title,c3.is_visible as c3_visible')
            ->order("g.display_order DESC,g.id DESC")
            ->paginate(10);

        $this->assign("list", $list);

        return $this->fetch();
    }

    //更改
    public function status()
    {
        if (request()->isAjax()) {
            //菜单ID
            $id = request()->param("id");
            //获取可见性状态
            $status = request()->param("status");

            try {
                //修改菜单显示隐藏
                $save = Db::name("sell_goods")
                    ->where("id", $id)
                    ->update(["status" => $status, 'update_time' => now_datetime()]);
                if ($status == 1) {
                    $log = '设置-商品-' . $id . '-上架';
                } else {
                    $log = '设置-商品-' . $id . '-下架';
                }

                if ($save) {
                    if ($status != 1) {
                        //下架商品删除 收藏 和 购物车
                        Db::name('sell_goods_car')->where('goods_id', $id)->delete();
                        Db::name('sell_goods_collection')->where('goods_id', $id)->delete();
                    }
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log . '成功！');

                } else {
                    Message::admin_log(0, $log);
                    $this->ajaxError($log . '失败');
                }
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }
    public function recommend()
    {
        if (request()->isAjax()) {
            //菜单ID
            $id = request()->param("id");
            //获取可见性状态
            $status = request()->param("recommend");

            try {
                //修改菜单显示隐藏
                $save = Db::name("sell_goods")
                    ->where("id", $id)
                    ->update(["is_recommend" => $status, 'update_time' => now_datetime()]);
                if ($status == 1) {
                    $log = '设置-商品-' . $id . '-首页推荐';
                } else {
                    $log = '设置-商品-' . $id . '-不推荐';
                }

                if ($save) {
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log . '成功！');

                } else {
                    Message::admin_log(0, $log);
                    $this->ajaxError($log . '失败');
                }
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //批量上架
    public function allUp()
    {
        if (request()->isAjax()) {

            $id_list = trim(request()->param("id_list"), ',');

            try {

                if (empty($id_list)) {
                    $this->ajaxError('请选择要上架的商品');
                }
                //修改菜单显示隐藏
                Db::name("sell_goods")
                    ->where("id", 'in', $id_list)
                    ->update(["status" => 1, 'update_time' => now_datetime()]);
                $log = '批量上架-商品-' . $id_list;
                Message::admin_log(0, $log);
                clear_cache();
                $this->ajaxSuccess($log . '成功！');
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //批量下架
    public function allDown()
    {
        if (request()->isAjax()) {
            $id_list = trim(request()->param("id_list"), ',');
            try {
                if (empty($id_list)) {
                    $this->ajaxError('请选择要下架的商品');
                }
                //修改菜单显示隐藏
                Db::name("sell_goods")
                    ->where("id", 'in', $id_list)
                    ->update(["status" => 0, 'update_time' => now_datetime()]);
                $log = '批量下架-商品-' . $id_list;
                //下架商品删除 收藏 和 购物车
                Db::name('sell_goods_car')->where('goods_id', 'in', $id_list)->delete();
                Db::name('sell_goods_collection')->where('goods_id', 'in', $id_list)->delete();
                Message::admin_log(0, $log);
                clear_cache();
                $this->ajaxSuccess($log . '成功！');
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //添加商品
    public function add()
    {
        $dispatch_type = get_dispatch_type();
        if (request()->isGet()) {
            $this->layoutModal();
            $this->assign('dispatch_type', $dispatch_type);
            return $this->fetch();
        }

        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );
            /********基础信息*********/
            //一二三分类
            $data['category_id1'] = intval(request()->param('category_id1'));
            $data['category_id2'] = intval(request()->param('category_id2'));
            $data['category_id3'] = intval(request()->param('category_id3'));

            //商品标题
            $data["title"] = trim(request()->param("title"));
            if (empty($data['title'])) {
                $this->ajaxError('请输入商品标题');
            }

            //商品短标题
            $data["short_title"] = trim(request()->param("short_title"));

            //关键字
            $data['keyword'] = trim(request()->param('keyword'));

            //商品缩略图
            $data["img_url"] = trim(request()->param("img_url"));
            if (empty($data['img_url'])) {
                $this->ajaxError('请上传商品缩略图');
            }

            //默认售价
            $data['price'] = round(request()->param('price'), 2);
            if ($data['price'] < 0.01) {
                $this->ajaxError('请正确输入默认售价，勿小于0.01元');
            }
            //默认原价
            $data['original_price'] = round(request()->param('original_price'), 2);
            if ($data['original_price'] < 0.01) {
                $this->ajaxError('请正确输入默认原价，勿小于0.01元');
            }

            $data['dispatch_type'] = intval(request()->param('dispatch_type'));
            if (empty($data['dispatch_type'])) {
                $this->ajaxError('请选择运费计算模式');
            }

            //运费
            $data['dispatch_price'] = round(request()->param('dispatch_price'), 2);
            if ($data['dispatch_price'] < 0) {
                $this->ajaxError('运费不可小于0');
            }
            //平台排序
            $data['display_order'] = intval(request()->param('display_order'));

            //显示销量
            $data['sales_nums'] = intval(request()->param('sales_nums'));

            //上架
            $data['status'] = intval(request()->param('status'));
            $data['is_recommend'] = intval(request()->param('is_recommend'));

            /********规格信息*********/
            //规格
            $data['use_spec'] = intval(request()->param('use_spec'));
            //规格标题
            $data['spec_name'] = trim(request()->param('spec_name'));
            if ($data['use_spec'] == 1) {
                //启用
                $data['stock'] = 0;
                if (empty($data['spec_name'])) {
                    $this->ajaxError('已启用规格，请输入规格标题');
                }
                if (!isset($_POST['spec'])) {
                    $this->ajaxError('已启用规格，请上传规格');
                }
                $spec = $_POST['spec'];
                if (!is_array($spec)) {
                    $this->ajaxError('规格格式有误');
                }

                $spec_data = [];

                foreach ($spec as $keys => $item) {

                    $spec_data[$keys]['title'] = trim($item['title']);
                    $spec_data[$keys]['img_url'] = trim($item['img_url']);
                    $spec_data[$keys]['price'] = round($item['price'], 2);
                    $spec_data[$keys]['original_price'] = round($item['original_price'], 2);
                    $spec_data[$keys]['stock'] = intval($item['stock']);
                    if (empty($spec_data[$keys]['title'])) {
                        $this->ajaxError('规格中有规格名称为空');
                    }
                    if (empty($spec_data[$keys]['img_url'])) {
                        $this->ajaxError('规格中有图片未上传');
                    }

                    if ($spec_data[$keys]['price'] < 0.01) {
                        $this->ajaxError('规格中有售价有误，勿小于0.01元');
                    }
                    if ($spec_data[$keys]['original_price'] < 0.01) {
                        $this->ajaxError('规格中有原价有误，勿小于0.01元');
                    }
                    $data['stock'] += $spec_data[$keys]['stock'];
                }

            } else {
                //默认库存
                $data['stock'] = intval(request()->param('stock'));
                $spec_data = false;
            }

            /********图文信息*********/
            //商品视频
            $data["video_url"] = trim(request()->param("video_url"));

            /********购买限制*********/
            //单次最多购买
            $data['maxbuy'] = trim(request()->param('maxbuy'));
            //单次最少购买
            $data['minbuy'] = trim(request()->param('minbuy'));
            //最多购买
            $data['allbuy'] = trim(request()->param('allbuy'));

            try {

                $da['detail'] = request()->param('article_detail');
                $detail_id = Db::name('sell_goods_detail')->insertGetId($da);
                $data['detail_id'] = $detail_id;
                $goods_id = Db::name("sell_goods")->insertGetId($data);
                $log = '添加-商品';
                if ($goods_id) {
                    if (is_array($spec_data)) {
                        foreach ($spec_data as $key => $item) {
                            $spec_data[$key]['goods_id'] = $goods_id;
                        }
                        Db::name('sell_goods_spec')->insertAll($spec_data);
                    }
                    if (isset($_POST['imglist']) && is_array($_POST['imglist'])) {
                        $img_data = [];
                        foreach ($_POST['imglist'] as $key => $item) {
                            $img_data[$key]['img_url'] = $item;
                            $img_data[$key]['goods_id'] = $goods_id;
                        }
                        Db::name('sell_goods_img')->insertAll($img_data);
                    }
                    $log .= '-' . $goods_id;
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log . '成功');
                } else {
                    //添加失败 抛出错误 之前的数据回滚
                    throw new Exception('添加商品失败');
                }

            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //删除规格
    public function removeSpec()
    {
        if (request()->isAjax()) {
            $spec_id = intval(request()->param('spec_id'));
            $goods_id = intval(request()->param('goods_id'));
            $del = Db::name('sell_goods_spec')
                ->where('id', $spec_id)
                ->where('goods_id', $goods_id)
                ->delete();
            $log = '删除-商品-' . $goods_id . '-规格-' . $spec_id;
            if ($del) {
                Message::admin_log(0, $log);
                return $this->ajaxSuccess('此规格删除成功');
            } else {
                Message::admin_log(0, $log);
                $this->ajaxError('此规格删除失败');
            }
        }
    }

    //编辑商品
    public function edit()
    {
        //商品id
        $id = intval(request()->param('id'));
        $info = Db::name('sell_goods')->where('id', $id)->find();

        $dispatch_type = get_dispatch_type();
        if (request()->isGet()) {
            $this->layoutModal();
            $this->assign('info', $info);
            //分类
            $this->assign('category_id1', $info['category_id1']);
            $this->assign('category_id2', $info['category_id2']);
            $this->assign('category_id3', $info['category_id3']);
            //处理缩略图
            $this->assign("single_image", array("img_url" => $info["img_url"]));
            //处理视频
            $this->assign("single_video", array("video_url" => $info["video_url"]));

            //规格
            $spec_list = Db::name('sell_goods_spec')->where('goods_id', $id)->select();
            $this->assign('spec_list', $spec_list);
            //商品附图
            $img_list = Db::name('sell_goods_img')->where('goods_id', $id)->field('img_url')->select();
            $img_list = array_column($img_list, 'img_url');
            $this->assign('multi_image', ['imglist' => $img_list]);
            //商品详情
            $detail = Db::name('sell_goods_detail')->where('id', $info['detail_id'])->value('detail');
            $this->assign("ueditor_content", array("article_detail" => $detail));

            $this->assign('dispatch_type', $dispatch_type);
            return $this->fetch();
        }

        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );

            //一二三分类
            $data['category_id1'] = intval(request()->param('category_id1'));
            $data['category_id2'] = intval(request()->param('category_id2'));
            $data['category_id3'] = intval(request()->param('category_id3'));

            //商品标题
            $data["title"] = trim(request()->param("title"));
            if (empty($data['title'])) {
                $this->ajaxError('请输入商品标题');
            }

            //商品短标题
            $data["short_title"] = trim(request()->param("short_title"));

            //关键字
            $data['keyword'] = trim(request()->param('keyword'));

            //商品缩略图
            $data["img_url"] = trim(request()->param("img_url"));
            if (empty($data['img_url'])) {
                $this->ajaxError('请上传商品缩略图');
            }

            //默认售价
            $data['price'] = round(request()->param('price'), 2);
            if ($data['price'] < 0.01) {
                $this->ajaxError('请正确输入默认售价，勿小于0.01元');
            }
            //默认原价
            $data['original_price'] = round(request()->param('original_price'), 2);
            if ($data['original_price'] < 0.01) {
                $this->ajaxError('请正确输入默认原价，勿小于0.01元');
            }
            $data['can_coin'] = round(input('can_coin'), 1);
            if ($data['can_coin'] < 0 || $data['can_coin'] > 100) {
                $this->ajaxError('可用' . config('coin_title') . '比例只能0%到100%之间');
            }

            $data['dispatch_type'] = intval(request()->param('dispatch_type'));
            if (empty($data['dispatch_type'])) {
                $this->ajaxError('请选择运费计算模式');
            }

            //运费
            $data['dispatch_price'] = round(request()->param('dispatch_price'), 2);
            if ($data['dispatch_price'] < 0) {
                $this->ajaxError('运费不可小于0');
            }
            //平台排序
            $data['display_order'] = intval(request()->param('display_order'));

            //显示销量
            $data['sales_nums'] = intval(request()->param('sales_nums'));

            //上架
            $data['status'] = intval(request()->param('status'));
            $data['is_recommend'] = intval(request()->param('is_recommend'));

            /********规格信息*********/
            //规格
            $data['use_spec'] = intval(request()->param('use_spec'));
            //规格标题
            $data['spec_name'] = trim(request()->param('spec_name'));
            if ($data['use_spec'] == 1) {
                //启用
                $data['stock'] = 0;
                if (empty($data['spec_name'])) {
                    $this->ajaxError('已启用规格，请输入规格标题');
                }
                if (!isset($_POST['spec'])) {
                    $this->ajaxError('已启用规格，请上传规格');
                }
                $spec = $_POST['spec'];
                if (!is_array($spec)) {
                    $this->ajaxError('规格格式有误');
                }

                $spec_data = [];

                foreach ($spec as $keys => $item) {
                    $spec_data[$keys]['id'] = intval($item['id']);
                    $spec_data[$keys]['title'] = trim($item['title']);
                    $spec_data[$keys]['img_url'] = trim($item['img_url']);
                    $spec_data[$keys]['price'] = round($item['price'], 2);
                    $spec_data[$keys]['original_price'] = round($item['original_price'], 2);
                    $spec_data[$keys]['stock'] = intval($item['stock']);
                    if (empty($spec_data[$keys]['title'])) {
                        $this->ajaxError('规格中有规格名称为空');
                    }
                    if (empty($spec_data[$keys]['img_url'])) {
                        $this->ajaxError('规格中有图片未上传');
                    }

                    if ($spec_data[$keys]['price'] < 0.01) {
                        $this->ajaxError('规格中有售价有误，勿小于0.01元');
                    }
                    if ($spec_data[$keys]['original_price'] < 0.01) {
                        $this->ajaxError('规格中有原价有误，勿小于0.01元');
                    }
                    $data['stock'] += $spec_data[$keys]['stock'];
                }

            } else {
                //默认库存
                $data['stock'] = intval(request()->param('stock'));
                $spec_data = false;
            }

            /********图文信息*********/
            //商品视频
            $data["video_url"] = trim(request()->param("video_url"));

            /********购买限制*********/
            //单次最多购买
            $data['maxbuy'] = trim(request()->param('maxbuy'));
            //单次最少购买
            $data['minbuy'] = trim(request()->param('minbuy'));
            //最多购买
            $data['allbuy'] = trim(request()->param('allbuy'));

            try {

                Db::name("sell_goods")->where('id', $id)->update($data);
                if ($data['status'] != 1) {
                    //下架商品删除 收藏 和 购物车
                    Db::name('sell_goods_car')->where('goods_id', $id)->delete();
                    Db::name('sell_goods_collection')->where('goods_id', $id)->delete();
                }

                if (is_array($spec_data)) {
                    foreach ($spec_data as $key => $item) {
                        if (!empty($spec_data[$key]['id'])) {
                            $spec_id = $spec_data[$key]['id'];
                            unset($spec_data[$key]['id']);
                            Db::name('sell_goods_spec')->where('id', $spec_id)->update($spec_data[$key]);
                            unset($spec_data[$key]);
                        } else {
                            unset($spec_data[$key]['id']);
                            $spec_data[$key]['goods_id'] = $id;
                        }

                    }
                    if (count($spec_data) > 0) {
                        Db::name('sell_goods_spec')->insertAll($spec_data);
                    }
                }
                Db::name('sell_goods_img')->where('goods_id', $id)->delete();
                if (isset($_POST['imglist']) && is_array($_POST['imglist'])) {
                    $img_data = [];
                    foreach ($_POST['imglist'] as $key => $item) {
                        $img_data[$key]['img_url'] = $item;
                        $img_data[$key]['goods_id'] = $id;
                    }
                    Db::name('sell_goods_img')->insertAll($img_data);
                }

                $da['detail'] = request()->param('article_detail');
                Db::name('sell_goods_detail')->where('id', $info['detail_id'])->update($da);
                Message::admin_log(0, '编辑-商品-' . $id);
                $this->ajaxSuccess('编辑商品成功');
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //删除商品
    public function remove()
    {
        if (request()->isAjax()) {
            //商品ID
            $id = request()->param("id");
            try {
                $check = Db::name('sell_order_goods')
                    ->alias('og')
                    ->join('sell_order o', 'o.id=og.orderid AND o.status=1')
                    ->where('og.goods_id', $id)
                    ->find();
                if ($check) {
                    $this->ajaxError('此商品还有未发货的订单，暂时无法删除');
                }

                $old = Db::name("sell_goods")
                    ->where("id", $id)
                    ->find();

                //更新商品
                $del = Db::name("sell_goods")
                    ->where("id", $id)
                    ->delete();
                $log = '删除-商品-' . $id . '-' . $old['title'];

                if ($del) {
                    //附表
                    Db::name('sell_goods_car')->where('goods_id', $id)->delete();
                    Db::name('sell_goods_collection')->where('goods_id', $id)->delete();
                    Db::name('sell_goods_detail')->where('id', $old['detail_id'])->delete();
                    Db::name('sell_goods_img')->where('goods_id', $id)->delete();
                    Db::name('sell_goods_spec')->where('goods_id', $id)->delete();
                    //清除缓存
                    clear_cache();
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess('商品删除成功');
                } else {
                    Message::admin_log(0, $log);
                    $this->ajaxError('商品删除失败');
                }
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

}